package com.example.demo.config;

import com.example.demo.constant.ApplicationConstant;
import com.example.demo.util.EnhancedRestTemplate;
import com.example.demo.util.JacksonUtils;
import com.example.demo.util.MyContextRefresher;
import com.example.demo.util.OkHttpUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Configuration
public class BaseConfig {

    @Value("${spring.application.name}")
    private String appName;
    @Value("${eureka.instance.hostname:localhost}")
    private String hostname;
    @Value("${server.port:8080}")
    private int port;


    @Bean(name = "hostName")
    public String getHostName() {
        log.info(">>>>>> 访问 http://{}:{} 可以查看{}服务信息", hostname, port, appName);
        try {
            if (StringUtils.isNotBlank(appName)) {
                appName = InetAddress.getLocalHost().getHostName();
            }
        } catch (UnknownHostException e) {
            log.error(">>>>>> UnknownHostException", e);
        }
        return appName;
    }


    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        return JacksonUtils.mapper;
    }

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        return new MappingJackson2HttpMessageConverter(objectMapper());
    }

    @Primary
    @Bean
    public OkHttpClient okHttpClient(ApplicationConstant applicationConstant){
        return OkHttpUtils.okHttpClientBuilder(applicationConstant).build();
    }

    @Primary
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter,
                                     OkHttpClient okHttpClient) {
        return EnhancedRestTemplate.assembleRestTemplate(mappingJackson2HttpMessageConverter, okHttpClient);
    }


    @Bean
    public RefreshScope scope(){
        return new RefreshScope();
    }

    @Bean
    public ContextRefresher contextRefresher(ConfigurableApplicationContext context,
                                             RefreshScope scope) {
        return new MyContextRefresher(context, scope);
    }



}
